{% extends 'base.html' %}
{% load staticfiles %}

{% block head %}
    <!-- Select2 -->
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/select2/dist/css/select2.min.css' %}">
    <link rel="stylesheet" href="{% static 'jquery-confirm/dist/jquery-confirm.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/steps.css' %}">
    <link rel="stylesheet" href="{% static 'css/toastr.min.css' %}">

    <style>
        .toast-vertical-center {
            top:10%;
            left:30%;
        }

        #toast-container>div {
            padding-top: 23px;
        }

        .step1-content {
            text-align: center;
            margin-bottom: 10px;
        }

        .step1-content button {
            width:100%;
            max-width: 300px;
        }
    </style>
{% endblock %}

{% block breadcrumb %}
    <h1>快速新增</h1>
    <ol class="breadcrumb">
        <li><a href="javascript:void(0);"><i class="fa fa-dashboard"></i> 仪表盘</a></li>
        <li><a href="javascript:void(0);"> 新增服务器连接方式</a></li>
    </ol>
{% endblock %}

{% block content %}
    <div class="row">
        <div class="col-xs-12">
            <div class="box box-primary" id="server_steps">
                <div class="box-header with-border">
                    <ul class="steps" style="margin-left: 0">
                        <li data-step="1" class="active">
                            <span class="step">1</span>
                            <span class="title">选择连接方式</span>
                        </li>
                        <li data-step="2">
                            <span class="step">2</span>
                            <span class="title">添加用户</span>
                        </li>
                        <li data-step="3">
                            <span class="step">3</span>
                            <span class="title">完成</span>
                        </li>
                    </ul>
                </div>
                <div class="box-body">
                    <div id="step1">
                        <div class="col-xs-12 col-lg-offset-4 col-lg-4 step1-content">
                            {% if connect_flag.ssh %}
                                {% if  connect_flag.ssh.server_status == 0 %}
                                    <button type="button" class="btn btn-primary" onclick="addFortServer('valid', {{ connect_flag.ssh.id }}, 'ssh', {{ connect_flag.ssh.port }});">解禁并进入SSH连接</button>
                                {% else %}
                                    <button type="button" class="btn btn-primary" onclick="addFortServer('update', {{ connect_flag.ssh.id }}, 'ssh', {{ connect_flag.ssh.port }});">进入SSH连接</button>
                                {% endif %}
                            {% else %}
                                    <button type="button" class="btn btn-primary" onclick="addFortServer('create', {{ server_ip.id }}, 'ssh');">新建SSH连接</button>
                            {% endif %}
                        </div>

                        <div class="col-xs-12 col-lg-offset-4 col-lg-4 step1-content">
                            {% if connect_flag.telnet %}
                                {% if  connect_flag.telnet.server_status == 0 %}
                                    <button type="button" class="btn btn-primary" onclick="addFortServer('valid', {{ connect_flag.telnet.id }}, 'telnet', {{ connect_flag.telnet.port }});">解禁并进入Telnet连接</button>
                                {% else %}
                                    <button type="button" class="btn btn-primary" onclick="addFortServer('update', {{ connect_flag.telnet.id }}, 'telnet', {{ connect_flag.telnet.port }});">进入Telnet连接</button>
                                {% endif %}
                            {% else %}
                                    <button type="button" class="btn btn-primary" onclick="addFortServer('create', {{ server_ip.id }}, 'telnet');">新建Telnet连接</button>
                            {% endif %}
                        </div>

                        <div class="col-xs-12 col-lg-offset-4 col-lg-4 step1-content">
                            {% if connect_flag.rdp %}
                                {% if  connect_flag.rdp.server_status == 0 %}
                                    <button type="button" class="btn btn-primary" onclick="addFortServer('valid', {{ connect_flag.rdp.id }}, 'rdp', {{ connect_flag.rdp.port }});">解禁并进入远程桌面连接</button>
                                {% else %}
                                    <button type="button" class="btn btn-primary" onclick="addFortServer('update', {{ connect_flag.rdp.id }}, 'rdp', {{ connect_flag.rdp.port }});">进入远程桌面连接</button>
                                {% endif %}
                            {% else %}
                                    <button type="button" class="btn btn-primary" onclick="addFortServer('create', {{ server_ip.id }}, 'rdp');">新建远程桌面连接</button>
                            {% endif %}
                        </div>
                    </div>
                    <div id="step2" style="display: none;">
                        <form class="main form-horizontal" id="fort_user_info" style="min-width: 500px;">
                            <div class="form-group" style="display: none;">
                                <label for="fort_server" class="col-sm-2 control-label"></label>
                                <div class="col-sm-6">
                                    <input type="text" class="form-control" name="fort_server" id="fort_server"/>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="fort_username" class="col-sm-2 control-label"><span class="text-red">*</span>用户名称</label>
                                <div class="col-sm-6">
                                    <input type="text" class="form-control" name="fort_username"
                                           id="fort_username" required/>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="fort_user_status" class="col-sm-2 control-label"><span class="text-red">*</span>用户状态</label>
                                <div class="col-sm-6">
                                    <select class="form-control" id="fort_user_status" name="fort_user_status" style="width: 100%;">
                                        {% for user_status in fort_user_status %}
                                            <option value="{{ user_status.0 }}" {% if user_status.0 == 1 %}selected{% endif %}>{{ user_status.1 }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>

                            <div class="form-group" id="form-password">
                                <label for="fort_password" class="col-sm-2 control-label"><span class="text-red">*</span>用户密码</label>
                                <div class="col-sm-6">
                                    <input type="password" class="form-control" name="fort_password"
                                           id="fort_password" required/>
                                </div>
                            </div>

                            <div class="form-group" id="form-fort_code">
                                <label for="fort_code" class="col-sm-2 control-label"><span class="text-red">*</span>字符编码</label>
                                <div class="col-sm-6">
                                    <select class="form-control" id="fort_code" name="fort_code" style="width: 100%;">
                                        {% for code in fort_code_ %}
                                            <option value="{{ code.0 }}" {% if user_status.0 == '1' %}selected{% endif %}>{{ code.1 }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="fort_belong_user" class="col-sm-2 control-label">所属用户</label>
                                <div class="col-sm-6">
                                    <select class="form-control select2" id="fort_belong_user"
                                            multiple="multiple" name="fort_belong_user"
                                            style="width: 100%;">
                                        {% for user in users %}
                                            <option value="{{ user.id }}">{{ user.username }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="fort_belong_group" class="col-sm-2 control-label">所属组</label>
                                <div class="col-sm-6">
                                    <select class="form-control select2" id="fort_belong_group"
                                            multiple="multiple" name="fort_belong_group"
                                            style="width: 100%;">
                                        {% for group in groups %}
                                            <option value="{{ group.id }}">{{ group.name }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="fort_user_memo" class="col-sm-2 control-label">用户说明</label>
                                <div class="col-sm-6">
                                    <textarea class="form-control" id="fort_user_memo"
                                              name="fort_user_memo"></textarea>
                                </div>
                            </div>
                            <div class="space-24"></div>
                        </form>
                    </div>
                    <div id="step3" style="display: none;">
                        <div style="text-align: center; height: 200px;">
                            <h1>新增成功！</h1>
                        </div>
                    </div>

                </div>
                <div class="box-footer">
                    <div id="step1-footer">
                        <button type="button" class="btn btn-default pull-right" onclick="history.go(-1)">返回</button>
                    </div>
                    <div id="step2-footer" style="display: none;">
                        <button type="button" class="btn btn-info pull-right" onclick="addStep2();">下一步</button>
                    </div>
                    <div id="step3-footer" style="display: none;">
                        <button type="button" class="btn btn-default pull-right" onclick="location.reload();">再次添加</button>
                        <button type="button" class="btn btn-info pull-right" onclick="location.href='/assets/assets_list/';">完成，返回资产列表</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
    <!-- Select2 -->
    <script src="{% static 'AdminLTE/bower_components/select2/dist/js/select2.full.min.js' %}"></script>
    <script src="{% static 'jquery-confirm/dist/jquery-confirm.min.js' %}"></script>
    <script src="{% static 'js/bootbox.js' %}"></script>
    <script src="{% static 'js/toastr.min.js' %}"></script>
    <script>
        $(function () {
            $('.select2').select2({
                allowClear: true
            });
            toastr.options = {
                "closeButton": true, //是否显示关闭按钮
                "positionClass": "toast-vertical-center",//弹出窗的位置
            }
        });

        function addFortServerMsg(type, server_port){
            var placeholder
            var value
            if(type == 'ssh'){
                placeholder = 'SSH连接默认端口为22'
                value=server_port||22
            } else if(type == 'telnet'){
                placeholder = 'Telnet连接默认端口为23'
                value=server_port||23
            } else{
                placeholder = 'RDP连接默认端口为3389'
                value=server_port||3389
            }
            return '<input type="number" class="form-control" name="port" id="port" min="1" value="'+value+'" max="99999" placeholder="'+placeholder+'" oninput="if(this.value==\'0\'){this.value=\'\';}else{this.value=this.value.replace(/[^0-9]/g,\'\')};if(this.value.length>5){this.value=this.value.slice(0,5)}">'
        }

        function step2Display(fortserver){
            document.getElementById('fort_user_info').reset()
            $(".select2").val('').trigger('change');
            $('#step1').hide()
            $('#step2').show()
            $('#step1-footer').hide()
            $('#step2-footer').show()
            $('li[data-step=1]').removeClass('active')
            $('li[data-step=2]').addClass('active')
            $('#fort_server').val(fortserver.id)
            var protocol = fortserver.server_protocol
            if (new Array('ssh', 'telnet').includes(protocol)) {
                    $('#form-fort_code').css('display', 'block');
                } else if (protocol === 'rdp') {
                    $('#form-fort_code').css('display', 'none');
                }
        }

        function step3Display(){
            $('#step2').hide()
            $('#step3').show()
            $('#step2-footer').hide()
            $('#step3-footer').show()
            $('li[data-step=2]').removeClass('active')
            $('li[data-step=3]').addClass('active')
        }

        function addErrorMessage(errors) {
            $.each(errors, function(name, value){
                if(name == 'non_field_errors'){
                    $('#fort_username').after('<span class="help-block">该用户已经存在!</span>')
                    $('#fort_username').parent().parent().addClass('has-error')
                }
                $.each(value, function(i, v){
                    $('#'+name).after('<span class="help-block">'+v+'</span>')
                })
                $('#'+name).parent().parent().addClass('has-error')
            })
        }

        function addStep2() {
            let data = {
                fort_server: $('#fort_server').val(),
                fort_username: $('#fort_username').val(),
                fort_password: $('#fort_password').val(),
                fort_user_status: $('#fort_user_status').val(),
                fort_user_memo: $('#fort_user_memo').val(),
                fort_belong_user: $('#fort_belong_user').val(),
                fort_belong_group: $('#fort_belong_group').val(),
                fort_code: $('#fort_code').val()||1
            };
            $('.help-block').remove()
            $('.form-group').removeClass('has-error')
            $.ajax({
                url: '/api/fort_user/',
                type: 'POST',
                data: JSON.stringify(data),
                dataType: 'json',
                contentType: "application/json",
                success: function () {
                    step3Display()
                },
                error: function (response) {
                    addErrorMessage(response.responseJSON)
                }
            });
        }

        function addFortServer(type, id, protocol, server_port){
            if(type == 'create'){
                bootbox.dialog({
                    title: '请确认连接端口',
                    message: addFortServerMsg(protocol),
                    onEscape: true,
                    backdrop: true,
                    buttons: {
                        ok: {
                            label: '确认',
                            className: 'btn-primary',
                            callback: function(){
                                var port = $('#port').val()
                                if(port.length == 0){
                                    $('#port').parent().addClass('has-error')
                                    toastr.error('该字段不能为空!')
                                    return false
                                }
                                $.ajax({
                                    url: '/api/fort/',
                                    type: 'POST',
                                    data: JSON.stringify({
                                        server: id,
                                        server_protocol: protocol,
                                        server_status: 1,
                                        port: port,
                                    }),
                                    dataType: 'json',
                                    contentType: "application/json",
                                    success: function (result) {
                                        step2Display(result)
                                    },
                                    error: function (response) {
                                        $.alert({
                                            title: 'Tips',
                                            type: 'red',
                                            content: response.responseText,
                                        })
                                    }
                                });
                            }
                        },
                        cancel: {
                            label: '关闭',
                            className: 'btn-danger',
                        },
                    }
                })
            } else {% if perms.fort.change_fortserver %}if(type == 'update'){
                bootbox.dialog({
                    title: '请确认连接端口',
                    message: addFortServerMsg(protocol, server_port),
                    onEscape: true,
                    backdrop: true,
                    buttons: {
                        ok: {
                            label: '确认',
                            className: 'btn-primary',
                            callback: function(){
                                var port = $('#port').val()
                                if(port.length == 0){
                                    $('#port').parent().addClass('has-error')
                                    toastr.error('该字段不能为空!')
                                    return false
                                }
                                $.ajax({
                                    url: '/api/fort/' + id + '/',
                                    type: 'PATCH',
                                    data: JSON.stringify({
                                        port: port,
                                    }),
                                    dataType: 'json',
                                    contentType: "application/json",
                                    success: function (result) {
                                        step2Display(result)
                                    },
                                    error: function (response) {
                                        $.alert({
                                            title: 'Tips',
                                            type: 'red',
                                            content: response.responseText,
                                        })
                                    }
                                });
                            }
                        },
                        cancel: {
                            label: '关闭',
                            className: 'btn-danger',
                        },
                    }
                })
            } else {
                bootbox.dialog({
                    title: '请确认连接端口',
                    message: addFortServerMsg(protocol, server_port),
                    onEscape: true,
                    backdrop: true,
                    buttons: {
                        ok: {
                            label: '确认',
                            className: 'btn-primary',
                            callback: function(){
                                var port = $('#port').val()
                                if(port.length == 0){
                                    $('#port').parent().addClass('has-error')
                                    toastr.error('该字段不能为空!')
                                    return false
                                }
                                $.ajax({
                                    url: '/api/fort/' + id + '/',
                                    type: 'PATCH',
                                    data: JSON.stringify({
                                        port: port,
                                        server_status: 1
                                    }),
                                    dataType: 'json',
                                    contentType: "application/json",
                                    success: function (result) {
                                        step2Display(result)
                                    },
                                    error: function (response) {
                                        $.alert({
                                            title: 'Tips',
                                            type: 'red',
                                            content: response.responseText,
                                        })
                                    }
                                });
                            }
                        },
                        cancel: {
                            label: '关闭',
                            className: 'btn-danger',
                        },
                    }
                })
            }{% else %}
                {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '抱歉！您没有更新堡垒机的权限！如有疑问，请联系管理员！',
                    });
                }
            {% endif %}
        }

    </script>
{% endblock %}